package com.example.teemor.es_demo.controller;

import com.example.teemor.es_demo.entity.ProductMySQL;
import com.example.teemor.es_demo.service.ProductService;
import com.example.teemor.es_demo.controller.UserController.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/admin/products")
@RequiredArgsConstructor
public class AdminProductController {

    private final ProductService productService;

    @PostMapping
    public ResponseEntity<ApiResponse<ProductMySQL>> createProduct(@Valid @RequestBody ProductMySQL product) {
        try {
            ProductMySQL savedProduct = productService.save(product);
            return ResponseEntity.ok(ApiResponse.success(savedProduct, "商品创建成功"));
        } catch (Exception e) {
            log.error("Failed to create product", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping
    public ResponseEntity<ApiResponse<Page<ProductMySQL>>> getAllProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<ProductMySQL> products = productService.findAll(pageable);
            return ResponseEntity.ok(ApiResponse.success(products, "获取商品列表成功"));
        } catch (Exception e) {
            log.error("Failed to get all products", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<ProductMySQL>> updateProduct(
            @PathVariable Long id,
            @Valid @RequestBody ProductMySQL productDetails) {
        try {
            ProductMySQL updatedProduct = productService.update(id, productDetails);
            return ResponseEntity.ok(ApiResponse.success(updatedProduct, "商品更新成功"));
        } catch (Exception e) {
            log.error("Failed to update product: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteProduct(@PathVariable Long id) {
        try {
            productService.deleteById(id);
            return ResponseEntity.ok(ApiResponse.success(null, "商品删除成功"));
        } catch (Exception e) {
            log.error("Failed to delete product: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getProductStats() {
        try {
            long totalProducts = productService.getProductCount();
            List<String> categories = productService.getAllCategories();
            List<String> brands = productService.getAllBrands();
            Map<String, Object> stats = Map.of(
                    "totalProducts", totalProducts,
                    "totalCategories", categories.size(),
                    "totalBrands", brands.size()
            );
            return ResponseEntity.ok(ApiResponse.success(stats, "获取商品统计成功"));
        } catch (Exception e) {
            log.error("Failed to get product stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}